<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="userProfile.photo"
            @click="imageClickFn"
          />
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        :value="userProfile.name"
        is-link
        @click="nameFn"
      />
      <van-cell
        title="生日"
        :value="userProfile.birthday"
        is-link
        @click="birthFn"
      />
    </van-cell-group>

    <!-- 用户名弹出框 -->
    <van-dialog
      v-model="show"
      title="用户名"
      show-cancel-button
      :before-close="beforeCloseFn"
    >
      <input type="text" v-fofo v-model="showName" />
    </van-dialog>

    <!-- 时间选择器 -->
    <van-popup
      v-model="dateTimePickerShow"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="dateCancelFn"
        @confirm="dateConfirmFn"
      />
    </van-popup>
  </div>
</template>

<script>
import { userProfileAPI, updatePhotoAPI, updateProfileAPI } from "@/api";
import { formatDate } from "@/utils/date.js";
import { MyNotify } from "@/utils/Notify";
import { mapMutations } from "vuex";
export default {
  name: "UserEdit",
  data() {
    return {
      userProfile: {},
      show: false,
      showName: "",
      minDate: new Date(1900, 0, 1), //起始时间
      maxDate: new Date(), //终止时间
      currentDate: new Date(), //当前时间,
      dateTimePickerShow: false, //是否显示时间选择器
    };
  },

  async created() {
    const res = await userProfileAPI();
    this.userProfile = res.data.data;
  },

  methods: {
    ...mapMutations(["SET_USERPHOTO", "SET_USERNAME"]),
    imageClickFn() {
      //js模拟input点击事件
      this.$refs.iptFile.click();
    },

    async onFileChange(e) {
      //用户可能没有选择图片，阻止代码往下执行
      if (e.target.files.length === 0) {
        return;
      }
      //创建一个表单对象
      const theFd = new FormData();
      //在表单对象中添加一个键值对
      theFd.append("photo", e.target.files[0]);
      const res = await updatePhotoAPI(theFd);
      //更新头像
      this.userProfile.photo = res.data.data.photo;
      //保存到vuex
      this.SET_USERPHOTO(res.data.data.photo);
    },

    //用户名点击事件
    nameFn() {
      this.show = true;
      this.showName = this.userProfile.name;
    },

    //提示框确认或取消前的回调函数
    async beforeCloseFn(action, done) {
      //点击的是确认按钮
      if (action === "confirm") {
        const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]{1,7}$/;
        if (reg.test(this.showName) === true) {
          //通过校验，关闭弹窗
          const res = await updateProfileAPI({ userName: this.showName });
          this.userProfile.name = this.showName; //回显用户名
          this.SET_USERNAME(this.showName); //保存到vuex
          done();
        } else {
          //未通过，给用户一个提示
          MyNotify({ type: "warning", message: "用户名只能是1-7位中英文组合" });
          done(false);
        }
      } else {
        //点击取消按钮，关闭弹窗
        done();
      }
    },

    //用户生日点击事件
    async birthFn() {
      this.dateTimePickerShow = true;
      this.currentDate = new Date(this.userProfile.birthday);
    },

    //时间选择器-取消事件
    dateCancelFn() {
      this.dateTimePickerShow = false; //关闭弹窗
    },

    //时间选择器-确认事件
    async dateConfirmFn() {
      //后端需要的时间格式位yyyy-mm-dd,所以这里需要格式化一下时间
      await updateProfileAPI({ birthday: formatDate(this.currentDate) });
      this.dateTimePickerShow = false; //关闭弹窗
      this.userProfile.birthday = formatDate(this.currentDate); //更新数据
    },
  },
};
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
/deep/ .van-dialog__content {
  text-align: center;
  input {
    padding: 0;
    border: none;
    outline: none;
    text-align: center;
  }
}
</style>
